<!-- src/views/MyFavoritesView.vue -->
<template>
  <div class="my-favorites-container" v-loading="loading">
    <el-page-header @back="$router.go(-1)" content="我的收藏" style="margin-bottom: 20px;" />

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      style="margin-bottom: 20px;"
    />

    <div v-if="favorites.length === 0 && !loading" class="no-favorites">
      <el-empty description="您还没有收藏过任何帖子" />
    </div>

    <div v-else class="favorites-content">
      <div class="favorites-stats" v-if="favorites.length > 0">
        <el-statistic title="收藏总数" :value="total" />
      </div>

      <el-card v-for="favorite in favorites" :key="favorite.postId" class="favorite-item">
        <div class="favorite-header">
          <el-link class="post-title" @click="goToPost(favorite.postId)" type="primary">
            {{ favorite.postTitle }}
          </el-link>
          <div class="post-badges">
            <el-tag v-if="favorite.postIsTop" type="danger" size="small" effect="dark">置顶</el-tag>
            <el-tag v-if="favorite.postIsEssence" type="warning" size="small" effect="light" style="margin-left: 8px;">精华</el-tag>
          </div>
        </div>

        <div class="favorite-meta">
          <div class="meta-left">
            <span class="meta-item">
              <el-icon><User /></el-icon>
              {{ favorite.postAuthorName }}
            </span>
            <span class="meta-item">
              <el-icon><Folder /></el-icon>
              {{ favorite.postCategoryName }}
            </span>
            <span class="meta-item">
              <el-icon><View /></el-icon>
              {{ favorite.postViewCount }}
            </span>
            <span class="meta-item">
              <el-icon><ChatDotRound /></el-icon>
              {{ favorite.postReplyCount }}
            </span>
            <span class="meta-item">
              <el-icon><Star /></el-icon>
              {{ favorite.postLikeCount }}
            </span>
          </div>

          <div class="meta-right">
            <span class="favorite-time">
              <el-icon><Clock /></el-icon>
              收藏于 {{ formatDate(favorite.favoritedAt || favorite.createdAt) }}
            </span>
          </div>
        </div>

        <div class="favorite-actions">
          <el-button size="small" @click="goToPost(favorite.postId)" type="primary" plain>
            查看帖子
          </el-button>
          <el-button size="small" @click="unFavoritePost(favorite.postId)" type="danger" plain>
            取消收藏
          </el-button>
        </div>
      </el-card>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: center;"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { getMyFavorites } from '@/services/userService';
import { ElMessage, ElMessageBox } from 'element-plus';
import { unfavoritePost } from '@/services/postService';
import dayjs from 'dayjs';
import {
  User,
  Folder,
  View,
  ChatDotRound,
  Star,
  Clock
} from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

const loading = ref(false);
const errorMessage = ref('');

const favorites = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 格式化日期
const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 跳转到帖子详情页
const goToPost = (postId) => {
  router.push(`/posts/${postId}`);
};

// 取消收藏帖子
const unFavoritePost = (postId) => {
  ElMessageBox.confirm(
    '确定要取消收藏这篇帖子吗？',
    '确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await unfavoritePost(postId);
      ElMessage.success('取消收藏成功');
      // 取消收藏成功后，刷新列表
      await fetchFavorites(currentPage.value, pageSize.value);
    } catch (error) {
      console.error('Unfavorite post failed:', error);
      errorMessage.value = error.response?.data?.message || '取消收藏失败';
      ElMessage.error(errorMessage.value);
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 获取我的收藏列表
const fetchFavorites = async (page = 1, size = 10) => {
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await getMyFavorites({
      page: page - 1, // 后端通常从 0 开始
      size: size
    });
    favorites.value = response.data.content || [];
    total.value = response.data.totalElements || response.data.total || 0;
    currentPage.value = page;
  } catch (error) {
    console.error('Failed to fetch my favorites:', error);
    errorMessage.value = error.response?.data?.message || '获取我的收藏列表失败';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 分页变化处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchFavorites(1, val);
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchFavorites(val, pageSize.value);
};

// 组件挂载时获取数据
onMounted(() => {
  fetchFavorites(currentPage.value, pageSize.value);
});
</script>

<style scoped>
.my-favorites-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.no-favorites {
  text-align: center;
  margin-top: 50px;
}

.favorites-stats {
  margin-bottom: 20px;
  text-align: center;
}

.favorite-item {
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.favorite-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.favorite-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.post-title {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  margin-right: 12px;
}

.post-badges {
  display: flex;
}

.favorite-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.meta-left {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 13px;
}

.meta-item .el-icon {
  margin-right: 4px;
}

.meta-right {
  display: flex;
}

.favorite-time {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 13px;
}

.favorite-time .el-icon {
  margin-right: 4px;
}

.favorite-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

@media (max-width: 768px) {
  .favorite-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .meta-left {
    gap: 12px;
  }

  .favorite-header {
    flex-direction: column;
    gap: 8px;
  }

  .post-badges {
    align-self: flex-start;
  }
}
</style>
